package com.szh.cloud.spring.security;

import com.szh.cloud.login.entity.LoginUserEntity;
import com.szh.cloud.login.service.LoginService;
import com.szh.cloud.mybatis.entity.PtUserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        String password = passwordEncoder.encode("123456");

        PtUserEntity ptUserEntity = loginService.queryUserInfoByName(username);
        if (ptUserEntity == null){
            throw new UsernameNotFoundException(username + " is not exit.");
        }

        List<GrantedAuthority> collection = new ArrayList<>();
        List<String> authList = loginService.queryAuthList(ptUserEntity.getUserUuid());
        for(String item:authList){
            collection.add(new SimpleGrantedAuthority("ROLE_" + item));
        }
        // 参数分别是：用户名，密码，用户权限
        LoginUserEntity user = new LoginUserEntity(ptUserEntity,username, collection);

        return user;
    }
}
